home *** CD-ROM | disk | FTP | other *** search
- Path: atglab.bls.com!Alun.Champion
- From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
- Newsgroups: comp.lang.c
- Subject: Re: swap high and low 16 bits?
- Date: 16 Jan 1996 16:00:16 GMT
- Organization: Computer People Inc.
- Message-ID: <ALUN.CHAMPION.96Jan16110016@g7240065.bridge.bst.bls.com>
- References: <Pine.OSF.3.91.960115174921.19742A-100000@io.UWinnipeg.ca>
- NNTP-Posting-Host: bstfirewall.bst.bls.com
- In-reply-to: Bill Simpson's message of Mon, 15 Jan 1996 17:55:15 -0600
-
- In article <Pine.OSF.3.91.960115174921.19742A-100000@io.UWinnipeg.ca> Bill Simpson <wsimpson@uwinnipeg.ca> writes:
-
- : I wanted to obtain a "random" starting number each time a program
- : is run. The obvious choice is time(NULL). The problem with it is that
- : if the program runs and terminates fairly quickly, the number returned by
- : time(NULL) is quite similar each run, differing only by the lowest bits.
-
- : One solution would be to swap the high 16 bits and the low 16 bits of the
- : 32 bit unsigned long int. Sorry this is dirty, not ANSI.
-
- : Could anyone please tell me how to do this? The simpler the code the
- : better (ANSI not important for this particular case).
-
- : Other solutions to the general problem (e.g. rotating the low bits to
- : the high end) are welcome.
-
- The way I understand you is that you are using the result of time() as your
- random number.
- The standard C library has a rand() function which can be seeded by
- the time() function with a call to srand(). A word of warning is that
- many of these rand() functions are notorious bad in the low order bits.
-
- Example for some range 0 to N-1:
- ...
- srand(time(0));
- ...
- rand() / (RAND_MAX / N + 1)
- ...
-
- See FAQ 13.16 and 13.17
-
- If you really want to swap the low 16 bits with the high 16 bits try:
- NB: Assumes 32 bit long's
-
- unsigned long a;
- a = (unsigned long)time(0);
- a = (a << 16) | (a >> 16);
-
- or more ANSI like - shift the low half bits with high half bits.
-
- #include <limits.h>
-
- unsigned long a;
- int shift = CHAR_BIT * sizeof(unsigned long) / 2
-
- a = (unsigned long)time(0);
- a = (a << shift) | (a >> shift);
-
- Hope this helps
- Regards
-
- -A.
-
- --
- | A.Champion |
-